﻿using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using WorkBasket.Data.Entities;
using WorkBasket.Data.Repository;
using WorkBasket.Infrastructure;
using WorkBasket.Models;

namespace WorkBasket.Controllers.Api
{
    [Authorize]
    public class ProcessVersionController : ApiController
    {

        private SOC soc = new SOC(new MyContext());
        [Route("api/ProcessVersion/GetByParentKey/{ParentKey}")]
        [HttpGet]
        public IHttpActionResult GetByParentKey(int ParentKey )
        {
           return Json( soc.ProcessVersions.Where(x => x.WorkflowID == ParentKey));
        }
        [HttpPost]
        [Route("api/ProcessVersion/save")]
        public IHttpActionResult Save([FromBody] ProcessVersion value)
        {
            try
            {


                if (value.ProcessVersionID == 0)
                {
                    soc.ProcessVersions.Add(value);
                }
                else
                {
                    soc.ProcessVersions.Update(value);
                }

                soc.CommitChanges();
                return Json(new DataReturn("Version Saved", value));
            }
            catch (Exception e)
            {
                return Json(new DataReturn(e.Message, e));
            }
        }
        [HttpPost]
        [Route("api/ProcessVersion/delete")]
        public IHttpActionResult Delete([FromBody] ProcessVersion value)
        {
            try
            {
                soc.ProcessVersions.Delete(value.ProcessVersionID);
                soc.CommitChanges();
                return Json(new DataReturn("Version Deleted", value));
            }
            catch (Exception e)
            {
                return Json(new DataReturn(e.Message, e));
            }
        }
        [Route("api/ProcessVersion/GetTreeJSON/{ID}")]
        public IHttpActionResult GetTreeJSON(int id)
        {
            return Json(soc.Execute<TreeNode>("StepsJsonFormat @ProcessVersionID", new SqlParameter("ProcessVersionID", id)));

        }

    }
}
 
